<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="hospital-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="名称" prop="name">
            <el-input v-model="postForm.name" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="省份" prop="provinceCode">
            <el-select
              v-model="postForm.provinceCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeProvince"
            >
              <el-option
                v-for="item in provinceOptions"
                :key="item.id"
                :label="item.province_name"
                :value="item.province_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="9">
          <el-form-item label="城市" prop="cityCode">
            <el-select
              v-model="postForm.cityCode"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
              @change="changeCity"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item.id"
                :label="item.city_name"
                :value="item.city_code"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="别名" prop="alias">
            <el-input v-model="postForm.alias" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="医院类型" prop="hcoType">
            <el-select
              v-model="postForm.hcoType"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in hcoTypeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="postForm.status"
              filterable
              clearable
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in statusOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getProvince,
  getCities,
  getHospitals
} from '@/api/baseData'
import {
  getHospitalStatus,
  getHospitalTypes,
  addHospital,
  updateHospital
} from '@/api/hospitals'

const defaultForm = {
  id: undefined,
  name: '',
  province: '',
  provinceCode: '',
  city: '',
  cityCode: '',
  alias: '',
  hcoType: undefined,
  status: undefined
}

export default {
  name: 'HospitalSettingForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      provinceOptions: [],
      cityOptions: [],
      hcoTypeOptions: [],
      statusOptions: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        // provinceCode: [
        //   { required: true, message: '请选择省份', trigger: 'change' }
        // ],
        // cityCode: [
        //   { required: true, message: '请选择城市', trigger: 'change' }
        // ],
        hcoType: [
          { required: true, message: '请选择医院类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.fetchProvince()
    this.fetchHospitalTypes()
    this.fetchHospitalStatus()
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchProvince() {
      getProvince().then(response => {
        // console.log(response)
        this.provinceOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchCities(code) {
      getCities({ provinceCode: code }).then(response => {
        // console.log(response)
        this.cityOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchHospitalTypes() {
      getHospitalTypes().then(response => {
        // console.log(response)
        this.hcoTypeOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchHospitalStatus() {
      getHospitalStatus().then(response => {
        // console.log(response)
        this.statusOptions = response.data
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      getHospitals({ id }).then(response => {
        const { data } = response
        // console.log(data)
        this.postForm.id = data[0].id
        this.postForm.name = data[0].name
        this.postForm.province = data[0].province
        this.postForm.provinceCode = data[0].provincecode
        this.postForm.city = data[0].city
        this.postForm.cityCode = data[0].citycode
        if (!this._.isEmpty(data[0].provincecode)) {
          this.fetchCities(data[0].provincecode)
        }
        this.postForm.alias = data[0].alias
        this.postForm.hcoType = data[0].hcoTypeId
        this.postForm.status = data[0].statusId
      }).catch(err => {
        console.log(err)
      })
    },
    changeProvince(province) {
      this.postForm.city = ''
      this.postForm.cityCode = ''
      this.cityOptions = []
      if (this._.isEmpty(province)) {
        this.postForm.province = ''
      } else {
        let provinceObj = {}
        provinceObj = this.provinceOptions.find((item) => {
          return item.province_code === province
        })
        this.postForm.province = provinceObj.province_name
        this.fetchCities(province)
      }
    },
    changeCity(city) {
      if (this._.isEmpty(city)) {
        this.postForm.city = ''
      } else {
        let cityObj = {}
        cityObj = this.cityOptions.find((item) => {
          return item.city_code === city
        })
        this.postForm.city = cityObj.city_name
      }
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            updateHospital(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addHospital(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .hospital-form {
    padding: 40px;
  }
}
</style>
